USE NHPLib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_proper') BEGIN
	DROP  FUNCTION  tsql.fn_proper
	PRINT '<<< DROP FUNCTION tsql.fn_proper - Completed with SUCCESS >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_proper
Type:			User defined function 
Owner:			
Description:	Returns the proper form of words 
Parameters:		@string = string to apply proper form to
Dependens on:  	none
Usage:			SELECT [tsql].[fn_proper] ('john adams')
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_proper&referringTitle=Documentation		
Version:		20120822
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		12/03/2009 - Adrian E Dudau - Function created
History:		08/22/2012 - Adrian E Dudau - Added references to project, SVN and Help
================================================================================================*/

CREATE FUNCTION	tsql.fn_proper
	(@string AS NVARCHAR(4000))
RETURNS NVARCHAR(4000)
	
BEGIN 
	DECLARE @Delimiter AS NVARCHAR(255)
	DECLARE @Pos AS BIGINT
	DECLARE @Buffer AS NVARCHAR(4000)
	DECLARE @Char AS NCHAR(1)
	DECLARE @PrevChar AS NCHAR(1)
	 
	SET @Buffer = ''
	SET @Char = ''
	SET @Pos = 1
	SET @Delimiter = ' -'''
	SET @String = LOWER(@string)

	WHILE @Pos <=  LEN(@string) BEGIN 
		SET @Char = SUBSTRING(@string,@Pos,1)
		SET @PrevChar = SUBSTRING(@string,@Pos-1,1)

		IF CHARINDEX(@PrevChar,@Delimiter,1) > 0 BEGIN 
			SET @Char = UPPER(@Char)
		END

		SET @Buffer = @Buffer + @Char

		SET @Pos = @Pos + 1
	END

	RETURN @Buffer 
END 

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------

IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_proper') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_proper - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_proper - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------






